<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width='800'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <a-form
      layout='horizontal'
      ref='form'
      :model='form'
      :rules='rules'
      :label-col='{ md: { span: 4 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 20 }, sm: { span: 24 } }'
    >
      <a-form-item label="所属牧场:" name="ranchId">
        <a-select
          show-search
          v-model:value="form.ranchId"
          placeholder="请选择所属牧场"
          style="width: 205px"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          allow-clear
        >
          <a-select-option v-for="item in ranchList" :key="item.ranchId" >
            {{ item.ranchName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="灭杀场所:" name="regionTarget">
        <a-select
          show-search
          v-model:value="form.regionTarget"
          placeholder="请选择灭杀场所"
          style="width: 100%"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          allow-clear
        >
          <a-select-option :value="1">牛场</a-select-option>
          <a-select-option :value="2">鸡鸭厂</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="灭杀目标:" name="killTarget">
        <a-select
          show-search
          v-model:value="form.killTarget"
          placeholder="请选择灭杀目标"
          style="width: 100%"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          allow-clear
        >
          <a-select-option :value="1">灭鼠</a-select-option>
          <a-select-option :value="2">灭蝇</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="服务类型:" name="serviceType">
        <a-select
          show-search
          v-model:value="form.serviceType"
          placeholder="请选择服务类型"
          style="width: 100%"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          allow-clear
        >
          <a-select-option :value="1">首次服务</a-select-option>
          <a-select-option :value="2">应急服务</a-select-option>
          <a-select-option :value="3">常规服务</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label='开始时间:' name='beginTime'>
        <a-date-picker v-model:value="form.beginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>

      <a-form-item label='结束时间:' name='endTime'>
        <a-date-picker v-model:value="form.endTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>

      <a-form-item label="服务用户:" name="serviceUser">
        <a-select
          show-search
          v-model:value="form.serviceUser"
          placeholder="请选择服务用户"
          style="width: 205px"
          :show-arrow="false"
          :filter-option="false"
          :not-found-content="null"
          allow-clear
        >
          <a-select-option v-for="item in selectUserList" :key="item.id" >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label='图片:' name='recordpics'>
        <a-upload
          name="file"
          :multiple="false"
          list-type="picture-card"
          :action="fileUploadUrl"
          :headers="headers"
          v-model:file-list="tempFileList"
          :before-upload="beforeUpload"
          @change="handleFileChange"
          @preview="handlePreview"
        >
          <div v-if="tempFileList.length < 8">
            <div class="ant-upload-text">点击上传</div>
          </div>

        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { InsectsServiceRecordApi } from '@/api/basf/InsectsServiceRecordApi';
import {RanchApi} from "@/api/property/RanchApi";
import {UserApi} from "@/api/system/user/UserApi";
import { message } from 'ant-design-vue';
import { FileUploadUrl as fileUploadUrlPrefix } from '@/api/system/operation/FileApi';
import {getToken} from "@/utils/token-util";
export default {
  name: 'BasfServicerecordInsectsServiceRecordEdit',
  components: {
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  created() {
    RanchApi.list({}).then(resp => {
      if (resp && resp.data &&  resp.data.length > 0) {
        this.ranchList = resp.data;
      }
    });

    UserApi.selectUserList({}).then(resp => {
      if (resp && resp.length > 0) {
        this.selectUserList = resp;
      }
    });

    if (this.data) {
      this.form = Object.assign({}, this.data);
      if (this.form.ranchId <= 0) {
        this.form.ranchId = undefined;
      }
      if (this.form.serviceUser < 0) {
        this.form.serviceUser = undefined;
      }
      this.isUpdate = true;
      if (this.data.pics) {
        console.log(this.data.pics);
        let picArr = this.data.pics.split(",");
        console.log(picArr);
        for (let i = 0;i < picArr.length; i++) {
          this.tempFileList.push({
            uid: i,
            name: 'image_' + i + '.png',
            status: 'done',
            url: picArr[i],
          });
        }
      }
      console.log(this.tempFileList);
    } else {
      this.form = {};
      this.isUpdate = false;
    }
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        regionTarget: [{ required: true, message: '请输入场域目标 1牛场 2鸡鸭厂', type: 'number', trigger: 'blur' }],
        killTarget: [{ required: true, message: '请输入灭杀目标 1灭鼠 2灭蝇', type: 'number', trigger: 'blur' }],
        serviceType: [{ required: true, message: '请输入服务类型 1首次服务、2应急服务、3常规服务', type: 'number', trigger: 'blur' }],
        beginTime: [{ required: true, message: '请输入开始时间', type: 'string', trigger: 'blur' }],
        endTime: [{ required: true, message: '请输入结束时间', type: 'string', trigger: 'blur' }],
        serviceUser: [{ required: true, message: '请输入执行用户', trigger: 'blur' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      ranchList : [],
      selectUserList : [],
      fileUploadUrl: `/api${fileUploadUrlPrefix}?secretFlag=N&fileDir=basf%2Frecordimage`,
      // 上传文件时候要带header
      headers: {
        Authorization: getToken()
      },
      // 临时存放文件列表（用来限制上传数量）
      tempFileList: [],
      // 查看图片的弹框
      previewVisible: false,
      // 预览图片的地址
      previewImage: null,
    }
  },
  methods: {
    /**
     * 保存和编辑
     *
     * @author cancan
     * @date 2024/11/18 23:25
     */
    async save() {
      // 校验表单
      await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;
      let result = null;
      let recordPics = [];
      console.log(this.tempFileList);
      if (this.tempFileList && this.tempFileList.length > 0) {
        for (let i=0; i < this.tempFileList.length; i++) {
          if (this.tempFileList[i].status == 'done' && this.tempFileList[i].response && this.tempFileList[i].response.data && this.tempFileList[i].response.data.fileUrl) {
            recordPics.push(this.tempFileList[i].response.data.fileUrl);
          } else if (this.tempFileList[i].status == 'done' && this.tempFileList[i].url) {
            recordPics.push(this.tempFileList[i].url);
          }
        }
      }
      if (recordPics.length > 0) {
        this.form.pics = recordPics.join(",");
      }
      // 执行编辑或修改
      if (this.isUpdate) {
        result = InsectsServiceRecordApi.edit(this.form);
      } else {
        result = InsectsServiceRecordApi.add(this.form);
      }
      console.log(this.form);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author cancan
     * @date 2024/11/18 23:25
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },

    /**
     * 上传图片前验证大小
     *
     * @author fengshuonan
     * @date 2022/3/28 13:56
     */
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('您只可以上传图片文件jpg或png，请检查文件格式');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('只能上传2M以内图片，请检查文件大小');
      }
      return isJpgOrPng && isLt2M;
    },

    /**
     * 预览图片
     *
     * @author fengshuonan
     * @date 2022/3/28 14:10
     */
    async handlePreview(file) {
      const getBase64 = file => {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = error => reject(error);
        });
      };
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewVisible = true;
      this.previewImage = file.url || file.preview;
    },

    /**
     * 取消预览图片
     *
     * @author fengshuonan
     * @date 2022/3/28 14:08
     */
    handleCancel() {
      this.previewVisible = false;
    },

    /**
     * 上传文件改变时的状态
     *
     * @param info 组件回调原有参数
     * @author fengshuonan
     * @date 2022/3/28 9:35
     */
    handleFileChange(info) {
      if (info.file.status === 'done') {
        // 设置临时fileList的值
        // console.log(info)
        // this.tempFileList.push(info.file);
        // 将文件属性名和文件编码存入数组中
        message.success(`${info.file.name} 图片上传成功`);
        // 设置表单对应的文件属性的值
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 图片上传失败`);
      }
    },
  }
};
</script>
